//
//  PersoniltyViewController.m
//  IntimateGift
//
//  Created by 张科 on 14-12-22.
//  Copyright (c) 2014年 蔡宏业. All rights reserved.
//

#import "PersoniltyViewController.h"
#import "NetHandler.h"
#import "PersonitlyCell.h"
#import "UIImageView+WebCache.h"
#import "UIColor+AddColor.h"
#import "DetailsViewController.h"
#import "UIScrollView+Extension.h"
#import "UIScrollView+MJRefresh.h"
@interface PersoniltyViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property(nonatomic, retain)NSMutableArray *arr;
@property(nonatomic, retain)UICollectionView *collectionView;
@property(nonatomic, assign)NSInteger num;
@end
@implementation PersoniltyViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.num = 12;
    }
    return self;
}
- (void)dealloc
{
    [_group release];
    [_arr release];
    [_collectionView release];
    [super dealloc];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.alpha = 1;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
  
}



- (void)handleData
{
    
    NSString *str = [[NSString alloc] initWithFormat:@"http://api.liwushuo.com/v1/channels/%@/items?limit=12&offset=0", self.group.Groupid];
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        NSError *error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSDictionary *detailDic = [NSDictionary dictionary];
        detailDic = [result objectForKey:@"data"];
        NSArray * detailArr = [detailDic objectForKey:@"items"];
        self.arr = [NSMutableArray array];
        for (NSDictionary *dicTemp in detailArr) {
            AllGroup *group = [[AllGroup alloc] initWithDictionary:dicTemp];
            [self.arr addObject:group];
            
        }
      
        [self installCollectionView];
        [self.collectionView reloadData];
        [self setupRefresh];
    }];
    
    
    
}

//- (void)viewWillAppear:(BOOL)animated
//{
//    self.navigationController.navigationBar.translucent = NO;
//}

- (void)viewDidLoad {
    // Do any additional setup after loading the view.
     self.navigationItem.title = self.group.name;
    self.navigationController.navigationBar.translucent = NO;
    NSLog(@"------%@", self.group.name);
    self.view.backgroundColor = [UIColor whiteColor];
    [self handleData];
    
}

- (void)installCollectionView
{
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.view.bounds.size.width / 4, 100);
    //滚动方向
    flowLayout.scrollDirection =  UICollectionViewScrollDirectionVertical;
    //最小item的间距
    flowLayout.minimumInteritemSpacing =2;
    //最小行间距
    flowLayout.minimumLineSpacing = 30;
//    flowLayout.headerReferenceSize = CGSizeMake(self.view.bounds.size.width, 66);
    //flowLayout.footerReferenceSize = CGSizeMake(100, 100);
    self.view.backgroundColor = [UIColor cyanColor];
    self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    [_collectionView release];
    
    //collectionView必须必须要注册一个cell类
    [self.collectionView registerClass:[PersonitlyCell class] forCellWithReuseIdentifier:@"repersonilty"];
    
    //collectionView 给section注册一个view显示内容
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerReuse"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PersonitlyCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"repersonilty" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    AllGroup *group = [[AllGroup alloc] init];
    group = [self.arr objectAtIndex:indexPath.item];
    NSString *str = [group.cover_image_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    [cell.perImageView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"zhanwei.jpg" ]];
    cell.liked_count.text = group.likes_count;
    cell.perLabel.text = group.title;
    return cell;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return  self.arr.count;
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerReuse" forIndexPath:indexPath];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(self.view.bounds.size.width /2.1, self.view.bounds.size.height / 3.0);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DetailsViewController *detVC = [[DetailsViewController alloc] init];
    detVC.mark = 2;
    AllGroup *allGroup = [self.arr objectAtIndex:indexPath.item];
    allGroup.name = self.group.name;
    detVC.group = allGroup;
    
    [self.navigationController pushViewController:detVC animated:YES];
//    [detVC release];

}


- (void)setupRefresh
{
    //    NSLog(@"进入了setupRefresh");
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    
    [self.collectionView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //进入刷新状态(一进入程序就下拉刷新)
    [self.collectionView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.collectionView addFooterWithTarget:self action:@selector(footerRereshing)];
}


- (void)headerRereshing
{
    NSString *str = [[NSString alloc] initWithFormat:@"http://api.liwushuo.com/v1/channels/%@/items?limit=12&offset=0", self.group.Groupid];
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        NSError *error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSDictionary *detailDic = [NSDictionary dictionary];
        detailDic = [result objectForKey:@"data"];
        NSArray * detailArr = [detailDic objectForKey:@"items"];
        [self.arr removeAllObjects];
        for (NSDictionary *dicTemp in detailArr) {
            AllGroup *group = [[AllGroup alloc] initWithDictionary:dicTemp];
            [self.arr addObject:group];
            
        }
        
        [self.collectionView reloadData];
    }];
    
    
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.collectionView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.collectionView headerEndRefreshing];
    });
}

//   进入加载状态
- (void)footerRereshing
{
    NSString *str = [[NSString alloc] initWithFormat:@"http://api.liwushuo.com/v1/channels/%@/items?limit=12&offset=%ld", self.group.Groupid, (long)self.num];
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        NSError *error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSDictionary *detailDic = [NSDictionary dictionary];
        detailDic = [result objectForKey:@"data"];
        NSArray * detailArr = [detailDic objectForKey:@"items"];
        
        for (NSDictionary *dicTemp in detailArr) {
            AllGroup *group = [[AllGroup alloc] initWithDictionary:dicTemp];
            [self.arr addObject:group];
            
        }
        self.num = self.num + 12;
        
    }];
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.collectionView  reloadData];
        [self.collectionView footerEndRefreshing];
    });
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
